<template>
  <el-dialog
    :model-value="visible"
    title="用户详情"
    width="800px"
    @close="handleClose"
  >
    <div v-loading="loading" class="user-detail">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">
          {{ userInfo.id }}
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ userInfo.username }}
        </el-descriptions-item>
        <el-descriptions-item label="手机号">
          {{ userInfo.phone }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">
          {{ userInfo.email }}
        </el-descriptions-item>
        <el-descriptions-item label="用户等级">
          <el-tag :type="getLevelTagType(userInfo.level)">
            {{ getLevelText(userInfo.level) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
            {{ userInfo.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="账户余额">
          <span class="balance">¥{{ userInfo.balance || '0.00' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="积分">
          {{ userInfo.points || 0 }}
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">
          {{ userInfo.registerTime }}
        </el-descriptions-item>
        <el-descriptions-item label="最后登录">
          {{ userInfo.lastLoginTime }}
        </el-descriptions-item>
        <el-descriptions-item label="注册IP" span="2">
          {{ userInfo.registerIp }}
        </el-descriptions-item>
        <el-descriptions-item label="真实姓名" span="2">
          {{ userInfo.realName || '未完善' }}
        </el-descriptions-item>
        <el-descriptions-item label="地址" span="2">
          {{ userInfo.address || '未完善' }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 用户统计 -->
      <div class="user-stats" v-if="userStats">
        <h4>用户统计</h4>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="总订单数" :value="userStats.totalOrders" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="完成订单" :value="userStats.completedOrders" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="总消费" :value="userStats.totalSpent" prefix="¥" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="平均客单价" :value="userStats.avgOrderValue" prefix="¥" />
          </el-col>
        </el-row>
      </div>

      <!-- 最近订单 -->
      <div class="recent-orders" v-if="recentOrders && recentOrders.length">
        <h4>最近订单</h4>
        <el-table :data="recentOrders" size="small">
          <el-table-column prop="orderNo" label="订单号" width="180" />
          <el-table-column prop="amount" label="金额" width="100">
            <template #default="{ row }">
              ¥{{ row.amount }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getOrderStatusType(row.status)">
                {{ getOrderStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" />
        </el-table>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="$router.push(`/users/${userId}/orders`)">
          查看全部订单
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { userAPI } from '@/api/user'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userId: {
    type: [String, Number],
    default: null
  }
})

const emit = defineEmits(['update:visible'])

// 响应式数据
const loading = ref(false)
const userInfo = ref({})
const userStats = ref(null)
const recentOrders = ref([])

// 获取用户详情
const fetchUserDetail = async () => {
  if (!props.userId) return

  loading.value = true
  try {
    const response = await userAPI.getDetail(props.userId)
    userInfo.value = response.data || {}

    // 获取用户统计
    try {
      const statsResponse = await userAPI.getUserStats(props.userId)
      userStats.value = statsResponse.data
    } catch (error) {
      console.error('获取用户统计失败:', error)
    }

    // 获取最近订单
    try {
      const ordersResponse = await userAPI.getRecentOrders(props.userId, { limit: 5 })
      recentOrders.value = ordersResponse.data || []
    } catch (error) {
      console.error('获取最近订单失败:', error)
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  } finally {
    loading.value = false
  }
}

// 获取等级文字
const getLevelText = (level) => {
  const levelMap = {
    1: '普通用户',
    2: 'VIP用户',
    3: '企业用户'
  }
  return levelMap[level] || '未知'
}

// 获取等级标签类型
const getLevelTagType = (level) => {
  const typeMap = {
    1: '',
    2: 'success',
    3: 'warning'
  }
  return typeMap[level] || ''
}

// 获取订单状态文字
const getOrderStatusText = (status) => {
  const statusMap = {
    1: '待付款',
    2: '进行中',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取订单状态标签类型
const getOrderStatusType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'primary',
    3: 'success',
    4: 'danger'
  }
  return typeMap[status] || ''
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
}

// 监听props变化
watch(() => props.visible, (visible) => {
  if (visible && props.userId) {
    fetchUserDetail()
  }
})
</script>

<style lang="scss" scoped>
.user-detail {
  .balance {
    font-weight: 500;
    color: #67c23a;
  }

  .user-stats {
    margin-top: 24px;

    h4 {
      margin-bottom: 16px;
      color: #2c3e50;
      font-weight: 600;
    }
  }

  .recent-orders {
    margin-top: 24px;

    h4 {
      margin-bottom: 16px;
      color: #2c3e50;
      font-weight: 600;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>